import sqlite3
import hashlib

DB_PATH = 'projmate.db'
SCHEMA_PATH = 'sql/schema.sql'

def hash_password(password: str) -> str:
    return hashlib.sha256(password.encode('utf-8')).hexdigest()

def init_db():
    with open(SCHEMA_PATH, 'r', encoding='utf-8') as f:
        schema_sql = f.read()
    conn = sqlite3.connect(DB_PATH)
    try:
        conn.executescript(schema_sql)
        # 插入默认用户 admin/123456
        cur = conn.cursor()
        cur.execute("SELECT COUNT(*) FROM user WHERE username=?", ("admin",))
        if cur.fetchone()[0] == 0:
            cur.execute(
                "INSERT INTO user (username, password, role) VALUES (?, ?, ?)",
                ("admin", hash_password("123456"), "admin")
            )
            conn.commit()
            print("已创建默认用户：admin/123456")
        print(f"数据库初始化成功，文件：{DB_PATH}")
    finally:
        conn.close()

if __name__ == '__main__':
    init_db() 